<template>
  <section class="component close-case-step">
    <el-form :model="formData" :rules="needErrorMsg? rules:{}" ref="close-case-step-form" label-width="100px">
      <el-form-item label="结案原因：" prop="closeReason">
        <el-select :disabled="isDetail" v-model="formData.closeReason">
          <el-option v-for="{index,name,code} in $dict.getDictData('CloseCaseCause')" :key="index" :label="name" :value="code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="垫付资本：" prop="advanceMoney">
            <el-input :disabled="isDetail" type="number" @input="(val)=>handleChange(val,'advanceMoney')" v-model="formData.advanceMoney"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成本：" prop="cost">
            <el-input :disabled="isDetail" type="number" v-model="formData.cost" @input="(val)=>handleChange(val,'cost')"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="收回金额：" prop="backMoney">
            <el-input :disabled="isDetail" type="number" v-model="formData.backMoney" @input="(val)=>handleChange(val,'backMoney')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="差额：" prop="difference">
            <el-input :disabled="isDetail" type="number" v-model="formData.difference" @input="(val)=>handleChange(val,'difference')"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="结案备注：" prop="closeRemark">
        <el-input :disabled="isDetail" type="textarea" v-model="formData.closeRemark" maxlength="200" show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <div class="text-center">
      <el-button @click="previousStepEmit">上一步</el-button>
      <el-button v-if="isShow" @click="submit" :loading="submitLoading">保存</el-button>
      <el-button @click="nextStepEmit">下一步</el-button>
    </div>
  </section>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { Prop, Emit, Inject } from "vue-property-decorator";
import { Dependencies } from '~/core/decorator';
import { CaseOperatorPageService } from '~/services/domain-service/case-operator-page.service';
import { CaseLegalRecordService } from '~/services/domain-service/case-legalRecord.service';
import { State, Action, Getter, namespace } from "vuex-class";
import { MENU_CHANNEL } from "~/config/enum.config";
import store from "~/store";
const CollectionExecutionModule = namespace('collection-execution');
@Component({
  components: {}
})

export default class CloseCaseStep extends Vue {
  @Dependencies(CaseOperatorPageService) private caseOperatorPageService: CaseOperatorPageService;
  @Dependencies(CaseLegalRecordService) private caseLegalRecordService: CaseLegalRecordService;
  @CollectionExecutionModule.State private caseId;
  @CollectionExecutionModule.State private menuChannel;
  @CollectionExecutionModule.State private otherData;
  @CollectionExecutionModule.Mutation private updateCurrentSavedStep;

  @Prop({ type: String, required: false }) private id;
  @Prop({ type: String }) private operatorId;
  @Prop({ type: Boolean }) private isDetail
  @Prop({ type: Boolean }) private needErrorMsg
  @State private userData

  private formData: any = {
    legalStage: "CLOSE",
    legalStatus: "CLOSING_CASE",
    id: "",
    closeReason: "MEDIATE",
    advanceMoney: "",
    cost: "",
    backMoney: "",
    difference: "",
    closeRemark: "",
  }
  private rules: any = {
    closeReason: [{ required: true, message: "请选择结案原因" }],
  }
  private submitLoading: boolean = false
  private get isShow () {
    const arr = [MENU_CHANNEL.Legal_personal, MENU_CHANNEL.Legal_team, MENU_CHANNEL.Assist_legal]
    if (arr.find(v => this.menuChannel === v)) {
      // 添加催记显示保存按钮 或编辑催记 与该登录用户一致显示
      if (!this.operatorId || this.operatorId === this.userData.id) return true
      else return false
    }
    return false
  }
  @Emit('nextStep') private nextStepEmit () {
    const form: any = this.$refs["close-case-step-form"];
    form.validate(valid => {
      if (!valid) return false;
    })

    // this.submit()
  }
  @Emit('previousStep') private previousStepEmit () { }
  @Emit('emitSuccess') private emitSuccess () {
    if (this.id) {
      this.showLegalInfoById(this.id);
    } else {
      // this.showLegalInfo();
    }
  }
  private mounted () {
    if (this.id) {
      this.showLegalInfoById(this.id)
    } else {
      // this.showLegalInfo();
    }
  }

  private handleChange (val, key) {
    if (val.length >= 20) {
      this.formData[key] = val.slice(0, 20)
      return
    }
  }


  private showLegalInfoById (val) {
    // 列表详情
    const vals = { "caseLegalRecordId": val }
    this.caseLegalRecordService
      .getCaseLegalRecordById(vals)
      .subscribe(
        (data) => {
          if (data) {
            this.formData.id = data.id;
            this.formData.closeReason = data.closeReason;
            this.formData.advanceMoney = data.advanceMoney;
            this.formData.cost = data.cost;
            this.formData.backMoney = data.backMoney;
            this.formData.difference = data.difference;
            this.formData.closeRemark = data.closeRemark;
          }
        },
        (err) => {

        },
      );
  }
  private showLegalInfo () {
    //查询上一条催记是否结案，回显数据
    this.caseOperatorPageService
      .queryUnClossCaseLegalRecord(this.caseId)
      .subscribe(
        (data) => {
          if (data) {
            this.formData.id = data.id;
          }
        },
        (err) => { },
      );
  }

  private setCurrentFormDataVal (step) {
    this.updateCurrentSavedStep(step)
    sessionStorage.setItem('currentFormDataVal', JSON.stringify(this.formData))
    setTimeout(() => {
      // this.formData = JSON.parse(sessionStorage.getItem('currentFormDataVal') || "") || {}
      const formData = JSON.parse(sessionStorage.getItem('currentFormDataVal') || "") || {}
      this.toInitData(formData)
    }, 300);
  }

  private toInitData (data) {
    const  formData = { ...data }
    for (const key in this.formData) {
      if (!['closeReason'].includes(key)) {
        formData[key] = ''
      }
    }
    this.formData = formData
  }

  private submit () {
    const form: any = this.$refs["close-case-step-form"];
    form.validate(valid => {
      if (!valid) return false;
      if (this.menuChannel === MENU_CHANNEL.Assist_legal) {
        this.formData.assistId = this.otherData.assistId;
      }
      this.formData.caseId = this.caseId;
      // this.formData.caseLegalRecordId = this.caseId;
      // this.formData.caseInfoRecordId = this.caseId;
      if (this.caseId && this.id) {
        this.setCurrentFormDataVal(3)
        this.caseLegalRecordService.editCaseLegalRecord(this.formData).subscribe(
          (data) => {
            form.resetFields();
            this.formData.id = "";
            this.emitSuccess();
            this.$message.success('法催催记立案已修改成功');
          },
          (err) => {
            this.submitLoading = false;
          },
        );
      } else {
        this.setCurrentFormDataVal(3)
        this.caseLegalRecordService.addCaseLegalRecord(this.formData).subscribe(
          (data) => {
            console.log('addCaselegga data', data);

            form.resetFields();
            this.formData.id = "";
            this.emitSuccess();
            this.$message.success('法催催记立案已添加成功，如需修改请在法务详情中进行修改');
            if (!data) { return false }
            store.commit('DataCaseIdFlag', data)
          },
          (err) => {
            this.submitLoading = false;
          },
        );
      }
    });
  }
}

</script>